﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using LRSystem;
using System.Timers;
using System.Windows.Threading;
using System.Windows.Forms;
using System.Diagnostics;//记得加入此引用
using System.Collections.ObjectModel;

namespace LoWoTSniffer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public CurrentBaudRate CurrentBaudRate { get; set; }    // 当前波特率
        public CurrentPort CurrentPort { get; set; }            // 当前的串口号
        public List<Port> PortList { get; set; }                // 串口Port名列表
        static LoWOTSerialPort sp;
        //private delegate void Log(string txt, bool isEnable);
        private ObservableCollection<baseReceivedPacket> pkRxList = new ObservableCollection<baseReceivedPacket>();
        private ObservableCollection<EndDevice> endList = new ObservableCollection<EndDevice>();
        private ColorRandom randomColor;
        private Dictionary<UInt16, UInt16> devdic = new Dictionary<ushort, ushort>();

        public MainWindow()
        {
            CurrentBaudRate = new CurrentBaudRate();
            CurrentPort = new CurrentPort();
            // 动态生成串口Port名列表
            string[] ports = SerialPort.GetPortNames();         // 获取目前可用的Port.
            if (ports.Length != 0)
                CurrentPort.Port = ports[0];
            PortList = new List<Port>();
            foreach (string port in ports)
            {
                PortList.Add(new Port(port));
            }


            DataContext = this;                                 // 设定相应XMAL的上下文

            randomColor = new ColorRandom(); // 用以随机生成RGB值

            LoWOTOriginalPacket.EvProcessReceivedPacket += sp_EvProcessRsp;
            InitializeComponent();
            PacketListCtrl.PacketItemsCtrl.ItemsSource = pkRxList;
            EnddeviceListCtrl.EndDeviceItemsCtrl.ItemsSource = endList;

        }

        private void OnOpenPort(object sender, RoutedEventArgs e)
        {
            try
            {
                sp = new LoWOTSerialPort(CurrentPort.Port, CurrentBaudRate.Rate);
                sp.Open();   // Open the serial port;

                OpenPortBtn.IsEnabled = false;
                ClosePortBtn.IsEnabled = true;
            }
            catch (Exception ipexp)
            {
                System.Windows.MessageBox.Show(ipexp.Message);
            }
        }

        void sp_EvProcessRsp(baseReceivedPacket pk)
        {

            try
            {
                //this.Dispatcher.BeginInvoke(()=>);
                Dispatcher.BeginInvoke((Action)(() =>
                {
                    //PacketListCtrl.PacketItemsCtrl.Items.Add(pk);

                    pkRxList.Add(pk);

                    if (pk is EnrollRequest)
                    {
                        if (!devdic.ContainsKey((pk as EnrollRequest).DNAddr))
                        {
                            EndDevice ed = new EndDevice();
                            byte rn = (pk as EnrollRequest).RN;
                            ed.bkColor = System.Windows.Media.Color.FromRgb(randomColor.rRandom[rn], randomColor.gRandom[rn], randomColor.bRandom[rn]);
                            ed.DNAddr = (pk as EnrollRequest).DNAddr;
                            ed.RN = rn;
                            endList.Add(ed);
                            EdViewer.ScrollToEnd();
                            devdic.Add(ed.DNAddr, ed.DNAddr);
                        }
                    }

                    if (pk is ConfirmedDataUp)
                    {
                        if(!devdic.ContainsKey((pk as ConfirmedDataUp).NodeAddr))
                        {
                            EndDevice ed = new EndDevice();
                            byte rn = (pk as ConfirmedDataUp).RN;
                            ed.bkColor = System.Windows.Media.Color.FromRgb(randomColor.rRandom[rn], randomColor.gRandom[rn], randomColor.bRandom[rn]);
                            ed.DNAddr = (pk as ConfirmedDataUp).NodeAddr;
                            ed.RN = rn;
                            endList.Add(ed);
                            EdViewer.ScrollToEnd();
                            devdic.Add(ed.DNAddr,ed.DNAddr);
                        }


                    }

                    PkViewer.ScrollToEnd();

                }));
            }
            catch (Exception ipexp)
            {
                System.Windows.MessageBox.Show(ipexp.Message);
            }

        }

        private void OnClosePort(object sender, RoutedEventArgs e)
        {
            if (sp != null)
                sp.Close();                     // Close serial port.
            OpenPortBtn.IsEnabled = true;
            ClosePortBtn.IsEnabled = false;
        }

        private void OnClosed(object sender, EventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }

    }
}
